function [bestp, bestq] = OptimizeGarch(r)

%% Optimize Q
global forecastDays;

% p=0;
% error = zeros(11,1);
% for q = 0:10
%     clear model
%     clear fit
%     
%     model = garchset('p',0,'q',q);
%     fit=garchfit(model,r);
%     [SigmaForecast,MeanForecast,SigmaTotal,MeanRMSE]=garchpred(fit,r,forecastDays);
%     error(q+1)=mean(MeanRMSE);
%     
% end
% 
% [minimo , bestq] = min(error);
% bestq=bestq-1;
%     
% 
% 
% 
% %% Optimize P
% close all
% error = zeros(11,1);
% for p = 0:10%p es garch
%     clear model
%     clear fit
%     
%     
%     model = garchset('p',p,'q',bestq);
%     fit=garchfit(model,r);
%     [SigmaForecast,MeanForecast,SigmaTotal,MeanRMSE]=garchpred(fit,r,forecastDays);
%     error(q+1)=mean(MeanRMSE);
%     
% end
% 
% [minimo , bestp] = min(error);
% bestp=bestp-1;
%garch( 0 ,3)
%% Optimize PQ
    close all
error = zeros(11,11);
for q = 0:10%q es arch
for p = 0:10%p es garch
    if  q==0
        p=0;

    end
    clear model
    clear fit
    model = garchset('p',p,'q',q);
    fit=garchfit(model,r);
    [SigmaForecast,MeanForecast,SigmaTotal,MeanRMSE]=garchpred(fit,r,forecastDays);
    error(p+1,q+1)=mean(MeanRMSE);
    
end
end
error(2:11,1)=error(1,1);
[fila,columna]=find(error==min(min(error)));
bestp=fila-1;
bestq = columna-1;

surf(error)%garch(0,3)